package com.example.service;

import com.example.entity.Coupon;
import com.example.repository.CouponRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class CouponService {
    
    @Autowired
    private CouponRepository couponRepository;
    
    // 获取所有优惠券
    public List<Coupon> getAllCoupons() {
        return couponRepository.findAll();
    }
    
    // 根据ID获取优惠券
    public Optional<Coupon> getCouponById(Long id) {
        return couponRepository.findById(id);
    }
    
    // 根据名称搜索优惠券
    public List<Coupon> searchCouponsByName(String name) {
        return couponRepository.findByCouponNameContaining(name);
    }
    
    // 根据状态获取优惠券
    public List<Coupon> getCouponsByStatus(Integer status) {
        return couponRepository.findByCouponStatus(status);
    }
    
    // 获取所有有效优惠券
    public List<Coupon> getActiveCoupons() {
        return couponRepository.findAllActiveCoupons();
    }
    
    // 创建新优惠券
    public Coupon createCoupon(String name, Integer status) {
        Coupon coupon = new Coupon(name, status);
        return couponRepository.save(coupon);
    }
    
    // 更新优惠券
    public Coupon updateCoupon(Long id, String name, Integer status) {
        Optional<Coupon> optionalCoupon = couponRepository.findById(id);
        if (optionalCoupon.isPresent()) {
            Coupon coupon = optionalCoupon.get();
            if (name != null) {
                coupon.setCouponName(name);
            }
            if (status != null) {
                coupon.setCouponStatus(status);
            }
            return couponRepository.save(coupon);
        }
        return null;
    }
    
    // 删除优惠券
    public boolean deleteCoupon(Long id) {
        if (couponRepository.existsById(id)) {
            couponRepository.deleteById(id);
            return true;
        }
        return false;
    }
    
    // 批量删除优惠券
    public void deleteCoupons(List<Long> ids) {
        couponRepository.deleteAllById(ids);
    }
    
    // 统计优惠券数量
    public long countCoupons() {
        return couponRepository.count();
    }
    
    // 统计指定状态的优惠券数量
    public long countCouponsByStatus(Integer status) {
        return couponRepository.findByCouponStatus(status).size();
    }
}
